package com.example.demo.chat_room.server.config;

import com.example.demo.chat_room.server.handler.PBServerHandler;
import com.example.demo.chat_room.server.handler.WebSocketFrameHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WebSocketStartConfig extends ChannelInitializer<SocketChannel> {

    @Autowired
    // 业务处理器
    PBServerHandler pbServerHandler;

    @Autowired
    NettyAndWebSocketConfig nWConfig;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline()
                // 使用Http编解码器
                .addLast(new HttpServerCodec())
                // 添加ChunkedWriteHandler处理器
                .addLast(new ChunkedWriteHandler())
                // 将多次请求的数据聚合起来
                .addLast(new HttpObjectAggregator(nWConfig.getAggregator()))
                // 访问地址以及将http协议升级为ws协议
                .addLast(new WebSocketServerProtocolHandler(nWConfig.getPath()))
                // WebSocket处理器,把数据转化为可用对象
                .addLast(new WebSocketFrameHandler())
                // 业务处理器
                .addLast(pbServerHandler);
    }
}
